<template>
  <div>
    <!-- 搜索表单 -->
    <el-row>
      <el-col :span="24">
        <el-form :inline="true" :model="queryItem">
          <el-form-item label="商品标题">
            <el-input v-model="queryItem.title" placeholder="商品标题" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryItem.status" placeholder="全部" clearable>
              <el-option label="全部" value="0" />
              <el-option label="正常" value="1" />
              <el-option label="禁用" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="添加时间">
            <el-date-picker
              v-model="createTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              :size="size"
            />
          </el-form-item>
          <el-form-item label="修改时间">
            <el-date-picker
              v-model="modifyTime"
              type="daterange"
              range-separator="To"
              start-placeholder="Start date"
              end-placeholder="End date"
              :size="size"
            />
          </el-form-item>
          <el-form-item label="价格">
            <el-col :span="11">
              <el-input v-model="price[0]" />
            </el-col>
            <el-col :span="1" style="text-align: center">-</el-col>
            <el-col :span="11">
              <el-input v-model="price[1]" />
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="doQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 功能按钮 -->
    <el-row>
      <el-col :span="24">
        <el-button style="margin: 5px 5px" type="primary" @click="editSelection"
          ><el-icon><EditPen /></el-icon>编辑</el-button
        >
        <el-button style="margin: 5px 5px" type="danger"
          ><el-icon><Delete /></el-icon>删除</el-button
        >
        <el-button
          @click="dialogSaveItemVisible = true"
          style="margin: 5px 5px"
          type="success"
          ><el-icon><Plus /></el-icon>新增</el-button
        >
      </el-col>
      <!-- 功能按钮 结束 -->
    </el-row>
    <!-- 列表 -->
    <el-row>
      <el-col :span="24">
        <!-- 用户列表 在el-table中通过属性data绑定我们要显示的列表数据 -->
        <el-table
          :data="items"
          max-height="500"
          style="width: 100%"
          :stripe="true"
          :border="true"
          :fit="true"
          ref="userTable"
        >
          <!-- 这里写列 -->
          <!-- type定义为selection,这一列会显示为复选框，自动实现全选功能 -->
          <el-table-column type="selection" />
          <!-- prop绑定要显示的属性的名字，label绑定列名 -->
          <el-table-column prop="itemId" label="编号" />
          <el-table-column prop="title" show-overflow-tooltip="title" label="商品标题" />
          <el-table-column prop="category.catName" label="商品类别" />
          <el-table-column prop="price" :formatter="priceFormatter" label="商品价格" />
          <el-table-column prop="stock" label="商品库存" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="modifyTime" label="修改时间" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag v-if="scope.row.status ==1" type="success">正常</el-tag>
              <el-tag v-else type="danger">禁用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <!-- 这里写的内容会放在默认的插槽中 -->
            <template #default="scope">
              <el-button
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格结束 -->
      </el-col>
    </el-row>

    <!-- 分页栏 -->
    <el-row>
      <el-col :span="24">
        <!-- 用户列表分页栏 -->
        <el-pagination
          background
          :page-size="limit"
          :total="total"
          layout="prev, pager, next, jumper, ->, total"
          @currentChange="handlerCurrentChange"
        ></el-pagination>
      </el-col>
    </el-row>
    <!-- 其他弹窗 -->
    <!-- 添加商品的弹窗 -->
    <el-dialog v-model="dialogSaveItemVisible" title="添加商品">
      <template #default>
        <el-form :model="newItem">
          <el-form-item label="商品类别" :label-width="formLabelWidth">
            <el-button @click="showChooseItemCat" type="primary"
              >选择类别</el-button
            ><el-tag v-if="this.currNode != undefined">{{
              currNode.catName
            }}</el-tag>
          </el-form-item>
          <el-form-item label="商品规格" :label-width="formLabelWidth">
            <el-button @click="showChooseSpeWin" type="primary"
              >选择规格</el-button
            >
            <el-tag v-for="spe in chooseSpes" :key="spe.speId">{{
              spe.speName
            }}</el-tag>
          </el-form-item>
          <el-form-item label="商品标题"  :label-width="formLabelWidth">
            <el-input
              v-model="newItem.title"
              placeholder="商品标题"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="商品卖点" :label-width="formLabelWidth">
            <el-input
              v-model="newItem.sellPoint"
              placeholder="商品卖点"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="商品库存" :label-width="formLabelWidth">
            <el-input
              v-model="newItem.stock"
              placeholder="商品库存"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="商品价格" :label-width="formLabelWidth">
            <el-input
              v-model="newItem.price"
              placeholder="商品价格"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="条形码" :label-width="formLabelWidth">
            <el-input
              v-model="newItem.barcode"
              placeholder="条形码"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://localhost:11011/cms/upload"
              list-type="picture-card"
              :on-success="handlerUploadSuccess"
              :on-remove="handleRemove"
              name="uploadFile"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品详情" :label-width="formLabelWidth">
            <Editor
              @contentChange="contentChange"
              width="600"
              height="300"
              content="请输入商品详情"
              uploadUrl="http://localhost:11011/cms/wangUpload"
            ></Editor>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <!-- 将抽屉收起来 -->
          <el-button
            @click="
              newItem = {};
              dialogSaveItemVisible = false;
            "
            >取消</el-button
          >
          <!-- 提交编辑之后的数据，关闭抽屉窗体，清空编辑对象。 -->
          <el-button type="primary" @click="doAddItem"> 提交 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择商品类别的弹窗 -->
    <el-dialog
      v-model="dialogChooseItemCatVisible"
      title="选择商品类别"
      width="30%"
    >
      <template #default>
        <el-tree
          :props="defaultProps"
          :data="treeData"
          @node-click="loadChildren"
          ref="catTree"
        />
      </template>
      <template #footer>
        <span class="dialog-footer">
          <!-- 将抽屉收起来 -->
          <el-button @click="dialogChooseItemCatVisible = false"
            >取消</el-button
          >
          <!-- 提交编辑之后的数据，关闭抽屉窗体，清空编辑对象。 -->
          <el-button type="primary" @click="doItemCatChoose"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 选择规格的弹窗 -->
    <el-dialog v-model="dialogChooseSpeCatVisible" title="选择商品规格">
      <template #default>
        <!-- 搜索表单 -->
        <el-row>
          <el-col :span="24">
            <el-form :inline="true" :model="querySpe">
              <el-form-item label="规格名称">
                <el-input v-model="querySpe.speName" placeholder="规格名称" />
              </el-form-item>
              <el-form-item label="状态">
                <el-select
                  v-model="querySpe.status"
                  placeholder="全部"
                  clearable
                >
                  <el-option label="全部" value="0" />
                  <el-option label="正常" value="1" />
                  <el-option label="禁用" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="doQuery">查询</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <!-- 列表开始 -->
        <el-row>
          <el-col :span="24">
            <el-table
              :data="spes"
              max-height="800"
              style="width: 100%"
              :stripe="true"
              :border="true"
              :fit="true"
              ref="speTable"
            >
              <el-table-column align="center" type="selection" />
              <el-table-column align="center" prop="speId" label="编号" />
              <el-table-column align="center" prop="speName" label="规格名称">
                <template #default="scope">
                  <el-link
                    @click="showEntryList(scope.row.speId)"
                    type="primary"
                    >{{ scope.row.speName }}</el-link
                  >
                </template>
              </el-table-column>
              <el-table-column align="center" prop="speDesc" label="规格说明" />

              <el-table-column
                align="center"
                prop="createTime"
                label="创建时间"
              />
              <el-table-column
                align="center"
                prop="modifyTime"
                label="修改时间"
              />
              <!-- 这里使用formatter绑定一个函数，用来格式化结果 -->
              <el-table-column align="center" prop="dictStatus" label="状态">
                <!-- 使用了table-column的插槽，显示对应的标签 -->
                <template #default="scope">
                  <el-tag
                    v-if="scope.row.status == 1"
                    class="ml-2"
                    type="success"
                    >正常</el-tag
                  >
                  <el-tag class="ml-2" type="danger" v-else>禁用</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <!-- 分页栏开始 -->
        <el-row>
          <el-col :span="24">
            <el-pagination
              background
              :page-size="limit"
              :total="total"
              layout="prev, pager, next, jumper, ->, total"
              @currentChange="handlerCurrentChange"
            ></el-pagination>
          </el-col>
        </el-row>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <!-- 将抽屉收起来 -->
          <el-button @click="dialogChooseSpeCatVisible = false">取消</el-button>
          <!-- 提交编辑之后的数据，关闭抽屉窗体，清空编辑对象。 -->
          <el-button type="primary" @click="doItemSpeChoose"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import itemCatHttp from "../../api/item-cat.js";
import speHttp from "../../api/item-spe.js";
import itemHttp from "../../api/item.js";
import Editor from "../../components/Editor/Editor.vue";
export default {
  components: { Editor },
  data() {
    return {
      items: [],
      currentPage: 1,
      limit: 10,
      total: 0,
      price: [], // 搜索栏中价格的范围
      createTime: [], //  搜索栏中创建时间的范围
      modifyTime: [], //  搜索栏中修改时间的范围
      queryItem: {}, // 商品的搜索对象
      dialogSaveItemVisible: false, // 添加商品的弹窗标记
      newItem: {}, //新增的商品对象
      itemDesc: {}, // 新增商品的详情对象
      // 商品类别相关的属性
      treeData: [], // 树的数据
      currNode: undefined, // 当前的选中的树的节点信息
      newCat: {}, // 保存新增内容类型的对象
      saveDialogVisible: false, // 新增窗体的标记
      defaultProps: {
        children: "children",
        label: "catName",
      },
      dialogChooseItemCatVisible: false, // 选择商品类目的弹窗标记
      // 商品规格相关属性
      dialogChooseSpeCatVisible: false, // 选择商品规格的弹窗标记
      spes: [], // spe数据列表
      querySpe: {}, // 搜索数据对象
      currentPage: 1, // 当前页面
      limit: 10, // 每页大小
      total: 0, //总条数
      chooseSpes: [], // 已经选择商品规格列表
      // 添加商品上传图片相关的内容：
      fileList: [], //  已经上传的图片的信息
    };
  },

  methods: {
    /**
     * 商品价格格式化
     */
    priceFormatter(row){
      return row.price / 100;
    },
    /**
     * 删除图片  file是要删除的文件的信息npm
     */
    handleRemove(file) {
      console.log(file);
    },
    // /**
    //  * 上传成功的事件  res 就是我们后端响应的result
    //  */
    // handlerUploadSuccess(res){
    //   console.log(res);
    //   // 将图片的信息加入fileList
    //   //this.fileList.push({url:res.msg});
    // },
    /**
     * 加载列表
     */
    loadItem() {
      // 发送请求
      // 组织查询对象
      if (this.price[0]) {
        this.queryItem.priceStart = this.price[0];
      }
      if (this.price[1]) {
        this.queryItem.priceEnd = this.price[1];
      }
      if (this.createTime[0]) {
        this.queryItem.createTimeStart = this.createTime[0];
      }
      if (this.createTime[1]) {
        this.queryItem.createTimeEnd = this.createTime[1];
      }
      if (this.modifyTime[0]) {
        this.queryItem.modifyTimeStart = this.modifyTime[0];
      }
      if (this.modifyTime[1]) {
        this.queryItem.modifyTimeEnd = this.modifyTime[1];
      }
      // 调用API进行查询
      itemHttp.list(this.queryItem, this.currentPage, this.limit, (res) => {
        this.items = res.data.records;
        this.total = res.data.total;
      });
    },
    /**
     * 富文本编辑器内容变化时的触发函数，参数就是最新的内容
     */
    contentChange(content) {
      this.itemDesc.itemDesc = content;
    },
    /**
     * 添加商品的提交按钮的事件
     */
    doAddItem() {
      //console.log(this.itemDesc.itemDesc);
      // 准备参数  组织speIds字符串
      let speIds = "";
      if (this.chooseSpes) {
        this.chooseSpes.forEach((spe) => (speIds += spe.speId + "_"));
        // 去掉最后的"_"
        speIds = speIds.substring(0, speIds.length - 1);
      }
      // 组织图片地址
      let image = "";
      if (this.fileList) {
        this.fileList.forEach((imgUrl) => (image += imgUrl.response.msg + ";"));
        image = image.substring(0, image.length - 1);
      }
      this.newItem.image = image;
      //  处理商品的价格
      this.newItem.price = parseInt(this.newItem.price * 100);
      // 调用API发送请求
      itemHttp.save(this.newItem, this.itemDesc.itemDesc, speIds, (res) => {
        if (res.code == "200") {
          this.$message({
            type: "success",
            message: "保存成功",
          });
          // 关闭窗体
          this.dialogSaveItemVisible = false;
          //  清空相关的属性
          this.newItem = {};
          this.itemDesc = {};
          this.chooseSpes = [];
          // 重新加载列表
          this.loadItem();
        } else {
          this.$message({
            type: "error",
            message: "保存失败",
          });
        }
      });
    },
    /**
     * 添加商品的表单中选择规格的按钮事件
     */
    showChooseSpeWin() {
      this.dialogChooseSpeCatVisible = true;
      this.loadSpe();
    },
    /**
     * 加载规格列表的方法
     */
    loadSpe() {
      speHttp.queryByPage(
        this.querySpe,
        this.currentPage,
        this.limit,
        (res) => {
          console.log(res);
          this.spes = res.data.records;
          this.total = res.data.total;
        }
      );
    },

    /**
     * 选择规格的确定事件
     */
    doItemSpeChoose() {
      // 找出已经选择好的spe对象
      this.chooseSpes = this.$refs.speTable.getSelectionRows();
      // 将选中的规格循环的显示在选择规格的按钮后。
      //  关闭窗体
      this.dialogChooseSpeCatVisible = false;
    },
    /**
     * 添加商品的窗体中选择类别的按钮事件
     */
    showChooseItemCat() {
      this.dialogChooseItemCatVisible = true;
      this.loadTreeData(0);
    },
    /**
     * 确定选择内容类别之后的提交按钮
     */
    doItemCatChoose() {
      // 判断是否选择了类目
      if (this.currNode == undefined) {
        this.$message({
          type: "info",
          message: "请选择一个类目",
        });
        return;
      }
      // 判断选择的类目是否是叶子节点
      if (this.currNode.parent != 0) {
        this.$message({
          type: "info",
          message: "请选择一个叶子类目",
        });
        return;
      }
      this.dialogChooseItemCatVisible = false;
      // 将选择的类目的内容显示在按钮的后面
      // 我们直接将currNode显示在选择类别的按钮的后面即可。
      // 将选择的类别的编号设置到newItem中
      this.newItem.catId = this.currNode.catId;
    },
    /**
     * 节点的单机事件
     */
    loadChildren(node) {
      // 纪录当前的节点信息
      this.currNode = node;
      if (node == undefined) {
        this.loadTreeData(0); // 直接加载根目录
      }
      // 判断是否有子节点
      else if (node.parent == 1) {
        //  说明有子节点
        // 加载子节点
        this.loadTreeData(node.catId, node);
      }
    },
    /**
     * 加载树的数据
     */
    loadTreeData(parentId, node) {
      itemCatHttp.queryByParentId(parentId, (res) => {
        // 将我们查询的数据传入pushTreeData
        this.pushTreeData(res.data, node);
      });
    },
    /**
     * 将对应的数据放入treeData对应的位置
     */
    pushTreeData(data, node) {
      if (this.treeData.length == 0 || node == undefined) {
        // 一级类目
        this.treeData = data;
      } else {
        // 非一级类目
        node.children = data;
      }
    },
    /**
     * 搜索按钮事件
     */
    doQuery() {},
  },
  mounted() {
    this.loadItem()
  },
};
</script>

<style scope>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>